﻿using System;
using System.Configuration;
using System.Data;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
using System.Web.UI.WebControls;
namespace ud_gSDMS.project
{
    public partial class approve_plan : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private string _id;
        //private string _idnew;
        private SiteUser siteUser;
        private int currentUserID = 0;

        void Page_Load(object sender, EventArgs e)
        {
            siteUser = SiteUtils.GetCurrentSiteUser();
            currentUserID = siteUser.UserId;
            //if (!UserCanEditPage() || !UserCanViewPage())
            //{
            //    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            //}
            
            if (SiteUtils.GetCurrentSiteUser() == null)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }

            if (!Page.IsPostBack)
            {
                PopulateLabels();
                PopulateControls();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    _id = Request["id"];
                    LoadGridMember(_id);
                    LoadData(_id);
                    LoadApprovePlan();
                    //LoadGridTimeSheet();
                }
            }
        }
        private void PopulateLabels()
        {

        }
        private void LoadGridMember(string id)
        {
            var data = gSDMS_BL.getMemberList(id);
            grdMember.DataSource = data;
            grdMember.DataBind();
        }

        private void LoadApprovePlan()
        {
            DataTable table = gSDMS_BL.ud_gSDMS_PROJECT_PLAN_Load(_id);
            grdApprovePlan.DataSource = table;
            grdApprovePlan.DataBind();
            ViewState["dataprojectplan"] = table;
        }

        private void PopulateControls()
        {
            var db = new gSDMS_DataLinq();
            const bool readOnly = true;
            txtProject_Code.ReadOnly = readOnly;
            txtProject_name.ReadOnly = readOnly;
            cboProject_leader.Enabled = !readOnly;
            txtMan_day.ReadOnly = readOnly;
            datKickoff_Date.ReadOnly = readOnly;
            datEnd_Date.ReadOnly = readOnly;
            txtFeedBack.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            txtFeedBack.WebEditor.Height = 200;
        }

        private static string projectid;
        private void LoadData(string id)
        {
            if (string.IsNullOrEmpty(id)) return;
            var db = new gSDMS_DataLinq();
            cboProject_leader.DataValueField = "UserID";
            cboProject_leader.DataTextField = "LoginName";
            cboProject_leader.DataSource = gSDMS_BL.mp_User_Search(null, null, null, null, null, null, 5.ToString());
            cboProject_leader.DataBind();

            var o = gSDMS_BL.ud_gSDMS_PROJECT_Get(id);
            if (o != null)
            {
                projectid = o.Project_ID.ToString();
                hidId.Value = o.Project_ID.ToString();
                if (o.CreatedOn != null) hidCreatedOn.Value = o.CreatedOn.Value.ToShortDateString();
                txtProject_Code.Text = o.ud_gSDMS_CONTRACT.Contract_Code;
                txtProject_name.Text = o.Name;
                cboProject_leader.SelectedValue = o.Project_Leader.ToString();
                datKickoff_Date.Text = o.Kickoff_Date.Value.Day + "/" + o.Kickoff_Date.Value.Month + "/" + o.Kickoff_Date.Value.Year;
                datEnd_Date.Text = o.End_Date.Value.Day + "/" + o.End_Date.Value.Month + "/"+ o.End_Date.Value.Year;
                txtMan_day.Text = o.Resource.ToString();//lay nguon nhan luc thuc te
                //load feedback neu co roi
                DataTable tb = gSDMS_BL.GetFeedBackProjectPlan(projectid);
                if (tb.Rows.Count > 0)
                {
                    txtFeedBack.Text = tb.Rows[0][0].ToString();
                }
                txtFeedBack.WebEditor.ToolBar = ToolBar.SimpleWithSource;
            }
        }
        #region event
        private int kt = 0;
        void btnSendFeedBack_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(projectid))
            {
                //update lai CAT_Project_Plan_Status_ID = 'Replan' and save feedBack Comment
                gSDMS_BL.ud_gSDMS_PROJECT_UpdStatusSendFeedBack(ref projectid, 3.ToString());
                var Project_Plan_ID = string.Empty;
                DataTable tb = (DataTable) ViewState["dataprojectplan"];
                string projectplan_id;
                foreach (DataRow row in tb.Rows)
                {
                    if (row["Project_Plan_ID"] != null) Project_Plan_ID = row["Project_Plan_ID"].ToString();
                    projectplan_id = row["Project_ID"].ToString();
                    if (projectplan_id == projectid)
                    {
                        gSDMS_BL.ud_gSDMS_PROJECT_PLAN_updFeedBack(Project_Plan_ID, txtFeedBack.Text);
                    }
                    kt = 1;
                }
                //viet ham gui mail cho GDDA nhac duyet 
                var userFrom = gSDMS_BL.mp_User_get(currentUserID.ToString(), null);
                //var emailFrom = siteUser.Email;
                var to = gSDMS_BL.mp_User_get(cboProject_leader.SelectedValue.ToString(), null);
                var cc = gSDMS_BL.mp_User_Lst("11");
                string emailCc = "";
                foreach (var mpUser in cc)
                {
                    emailCc += mpUser.Email + ", ";
                }
                //var emailTo = gSDMS_BL.ud_gSDMS_PROJECT_Get(projectid).ud_gSDMS_CONTRACT.mp_User1.Email;
                var subject = string.Format("[gSDMS-Project Plan] CHANGE STATUS IN PROJECT : {0} FROM gSDMS", txtProject_name.Text);
                var textBody = "<b>From: </b>" + userFrom.Name + " [mailto: ] " + userFrom.Email + "]" +
                           "<br/><b>Send: </b>" +
                           DateTime.Now.ToLongDateString() + "<br/><b>To: </b>" +
                           to.Name + "; " + to.Email + "<br/><b>CC: </b>" + emailCc + "<br/><b>Subject: </b>" +
                           txtProject_name.Text + "_Status<br/><br/><b>Dear </b>" + to.LoginName +
                           ",<br/><br/><li>Please edit about this project: " + txtProject_Code.Text +
                           "</li><br/><li>And then please to change status suitable...</li>"+
                           "<br/><br/> Please click here to change : " + SiteRoot +
                           "/gSDMSModule/project/Changestatus.aspx?pageid=16&id=" + projectid +
                           "<br/><br/><i>" +txtFeedBack.Text +"</i><br/><br/>Regard...!<br/>" + userFrom.Name;
                var siteGuid = siteSettings.SiteGuid;
                Library.SendMail(userFrom.Email, to.Email, emailCc, string.Empty, subject, textBody, siteGuid);
                //va chuyen tinh trang du an sang wait approve
            }
            if (kt == 1)
            {
                lblMes.Text = "Changed: status => 'Replan'. <br/> You send to FeedBack success...";
                lblMes.Visible = true;
            }
            else
            {
                    lblMes.Text = "You not change success. Please see again...";
                    lblMes.Visible = true;
            }
        }

        void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                _id = hidId.Value;
                //update lai CAT_Project_Plan_Status_ID = 'Approved' and CAT_Project_Step_ID = 'Design'		
                if (!string.IsNullOrEmpty(projectid))
                {
                    gSDMS_BL.ud_gSDMS_PROJECT_UpdStatusAndStep(ref projectid, 6.ToString(), 4.ToString());
                    lblMes.Text = "Updated success : Status => Approved, and Work Step => Design. <br/> You had send message to project manage...";
                    lblMes.Visible = true;
                }

                //Gửi mail báo quản trị dự án. Nhắc quản trị dự án chuyển trang thái dự án sang tình trạng phù hợp
                var userFrom = gSDMS_BL.mp_User_get(currentUserID.ToString(), null);
                //var emailFrom = siteUser.Email;
                var to = gSDMS_BL.mp_User_get(cboProject_leader.SelectedValue.ToString(), null);
                var cc = gSDMS_BL.mp_User_Lst("11");
                string emailCc = "";
                foreach (var mpUser in cc)
                {
                    emailCc += mpUser.Email + ", ";
                }
                //var emailTo = gSDMS_BL.ud_gSDMS_PROJECT_Get(projectid).ud_gSDMS_CONTRACT.mp_User1.Email;
                var subject = string.Format("[gSDMS-Project Plan] CHANGE STATUS IN PROJECT : {0} FROM gSDMS", txtProject_name.Text);
                var textBody = "<b>From: </b>" + userFrom.Name + " [mailto: ] " + userFrom.Email + "]" +
                           "<br/><b>Send: </b>" +
                           DateTime.Now.ToLongDateString() + "<br/><b>To: </b>" +
                           to.Name + "; " + to.Email + "<br/><b>CC: </b>" + emailCc + "<br/><b>Subject: </b>" +
                           txtProject_name.Text + "_Status<br/><br/><b>Dear </b>" + to.LoginName +
                           ",<br/><br/><li>Please edit about this project: " + txtProject_Code.Text +
                           "</li><br/><li>And then please to change status suitable...</li>" +
                           "<br/><br/> Please click here to change : " + SiteRoot +
                           "/gSDMSModule/project/Changestatus.aspx?pageid=16&id=" + projectid +
                           "<br/><br/>Regard...!<br/>" + userFrom.Name;
                var siteGuid = siteSettings.SiteGuid;
                Library.SendMail(userFrom.Email, to.Email, emailCc, string.Empty, subject, textBody, siteGuid);
                //va chuyen tinh trang du an sang wait approve
            }
            catch (Exception ex)
            {
                lblMes.Text = ex.Message;
                lblMes.Visible = true;
            }
        }
       void grdApprovePlan_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["Direction"] == null) ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " ASC") ViewState["Direction"] = " DESC";
            else if (ViewState["Direction"].ToString() == " DESC") ViewState["Direction"] = " ASC";
            //grdProjectPlan.EditIndex = -1;
            string strSortExp = e.SortExpression + ViewState["Direction"].ToString();
            ViewState["SortExpression"] = strSortExp;
            LoadApprovePlan();
        }
        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            btnApprove.Click += btnApprove_Click;
            btnSendFeedBack.Click += btnSendFeedBack_Click;
            grdApprovePlan.Sorting += grdApprovePlan_Sorting;
            SiteUtils.SetupEditor(txtFeedBack);
            SuppressPageMenu();
        }
        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            //config = new ContactFormConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion

        protected void txtContract_Code_TextChanged(object sender, EventArgs e)
        {

        }
    }
}